package org.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


// 心跳清理器 用于清理超过60秒没有心跳的服务  并通知监听者
@Service
public class HeartbeatCleaner {

    @Autowired
    private ServiceContext serviceContext;

    @Autowired
    private ListenerContext listenerContext;


    // 定时任务，定期清理超时服务
    @PostConstruct
    public void startCleaning() {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(this::cleanStaleServices, 0, 6, TimeUnit.SECONDS);
        System.out.println("定时清理服务启动");
    }

    // 清理超过6秒没有心跳的服务
    private void cleanStaleServices() {
        long now = System.currentTimeMillis();
        System.out.println("开始清理超时服务");

        Set<ServiceInstance> toRemove = new HashSet<>();

        //遍历所有服务 加入待删除集合
        for (Map.Entry<String, Collection<ServiceInstance>> entry : serviceContext.getAllServices().entrySet()) {
           for(ServiceInstance serviceInstance : entry.getValue()){
               if (now - serviceInstance.getLastHeartbeat() > 6000) {
                   toRemove.add(serviceInstance);
               }
           }

        }

        //遍历待删除集合 删除服务 并通知监听者
        for(ServiceInstance serviceInstance : toRemove){
            System.out.println("超时服务被清理: " +serviceInstance.getServiceName()+
                    serviceInstance.getIp()+":"+serviceInstance.getPort());
            System.out.println(now + " - " + serviceInstance.getLastHeartbeat() + " - " + serviceInstance.getServiceName());
            serviceContext.removeServicesByServiceInstance(serviceInstance);

            listenerContext.notifyListeners(new ServiceChangeEvent(serviceInstance,
                    ChangeType.LOGOUT));

        }
        System.out.println("超时服务被清理完成 剩余服务数量：" + serviceContext.getServiceCount());

    }
}
